package cn.ultrarisk.scadmin.manager.biz.zookeeper.service;

import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.scadmin.manager.biz.common.context.OperationType;
import cn.ultrarisk.scadmin.manager.biz.common.service.OperationLogService;
import cn.ultrarisk.scadmin.manager.biz.solr.valid.ZKBackupValidator;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.dao.ZkBackupDAO;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.entity.ZkBackup;
import cn.ultrarisk.scadmin.manager.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * zk备份数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ZkBackupService {
    @Autowired
    private ZkBackupDAO zkBackupDAO;
    @Autowired
    private ZkNodeService zkNodeService;
    @Autowired
    private ZKBackupValidator validator;
    @Autowired
    private OperationLogService operationLogService;

    public void create(String path, String remark, Integer type) {
        validator.validPath(path);

        ZkBackup backup = new ZkBackup();
        backup.setType(type);
        backup.setPath(path);
        backup.setRemark(remark);
        backup.setCreateTime(System.currentTimeMillis());
        zkBackupDAO.create(backup);

        zkNodeService.saveByZKPath(path, backup.getId());
        operationLogService.createZKBackupLog(OperationType.ZK_BACKUP_CREATE, backup.getId());
    }

    public void delete(Integer id) {
        operationLogService.createZKBackupLog(OperationType.ZK_BACKUP_DELETE, id);
        zkBackupDAO.delete(id);
        zkNodeService.deleteByBackupId(id);
    }

    /**
     * 清除过期的ZKBackup数据
     *
     * @query expiredTime
     */
    public void clearExpiredData(long expiredTime) {
        Query query = Query.ltQuery(ZkBackup.CREATE_TIME, expiredTime);
        List<Integer> backupIds = zkBackupDAO.findColumn(query, ZkBackup.ID, true, true);
        if (CollectionUtil.isNotEmpty(backupIds)) {
            zkNodeService.deleteByBackupId(backupIds.toArray(new Integer[backupIds.size()]));
        }
        zkBackupDAO.delete(query);
    }
}